# coding=utf-8
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import json

from .forms import LoginForm
from .models import User
from .models import Warehouse
from .models import Item
# Create your views here.

def index(request):
	if(request.session.get("username",default=None)==None):
		return HttpResponseRedirect(reverse("login"));
	warehouseList=[]
	whs=Warehouse.objects.all()
	for w in whs:
		nw={}
		nw["id"]=w.id
		nw["name"]=w.name
		nw["accountId"]=w.accountId
		nw["isLockBlock"]=w.isLockBlock
		nw["blockLockUser"]=w.blockLockUser
		nw["blockLockUsername"]=""
		if(w.isLockBlock):
			lu=User.objects.get(id=w.blockLockUser)
			nw["blockLockUsername"]=lu.username
		nw["items"]=[]
		iCount=0
		items=Item.objects.filter(warehouse=w)
		for i in items:
			iCount+=i.count
			ni={}
			ni["id"]=i.id
			ni["name"]=i.name
			ni["count"]=i.count
			ni["isLock"]=i.isLock
			ni["lockUser"]=i.lockUser
			ni["lockUsername"]=""
			if(i.isLock):
				ilu=User.objects.get(id=i.lockUser)
				ni["lockUsername"]=ilu.username
			nw["items"].append(ni)


		nw["remain"]=w.totalBlock-iCount
    		warehouseList.append(nw)

	
	return render(request,"index.html", {"warehouseList": warehouseList});

def login(request):

	if(request.method=="POST"):
		form=LoginForm(request.POST)
		if(form.is_valid()):
			username = form.cleaned_data['username']
			pwd = form.cleaned_data['password']
			try:
				nu=User.objects.filter(username=username).get(password=pwd)
			except:
				return render(request,"login.html",{"message":"用户名或密码错误"});
			request.session['username']=username
			request.session['userId']=nu.id
			return HttpResponseRedirect(reverse("index"));

	return render(request,"login.html");


def logout(request):
	try:
		del request.session['username']
		del request.session['userId']
	except KeyError:
		pass
	return HttpResponseRedirect(reverse("login"));


def lockBlock(request):
	userId=request.GET["userId"]
	warehouseId=request.GET["warehouseId"]
	user=User.objects.get(id=userId)
	wh=Warehouse.objects.get(id=warehouseId)

	wh.isLockBlock=True
	wh.blockLockUser=userId
	wh.save()
	return HttpResponse(json.dumps({"success":True}), content_type="application/json")

def unlockBlock(request):
	warehouseId=request.GET["warehouseId"]
	wh=Warehouse.objects.get(id=warehouseId)

	wh.isLockBlock=False
	wh.blockLockUser=None
	wh.save()
	return HttpResponse(json.dumps({"success":True}), content_type="application/json")

def addNewItem(request):
	warehouseId=request.GET["warehouseId"]
	name=request.GET["name"]
	count=request.GET["count"]
	wh=Warehouse.objects.get(id=warehouseId)

	nitem=Item.objects.create(name=name, count=count,warehouse=wh)
	nitem.save()
	return HttpResponse(json.dumps({"success":True}), content_type="application/json")

def lockItem(request):
	userId=request.GET["userId"]
	itemId=request.GET["itemId"]
	user=User.objects.get(id=userId)
	item=Item.objects.get(id=itemId)

	item.isLock=True
	item.lockUser=userId
	item.save()
	return HttpResponse(json.dumps({"success":True}), content_type="application/json")

def unlockItem(request):
	useCount=int(request.GET["useCount"])
	itemId=request.GET["itemId"]
	item=Item.objects.get(id=itemId)

	if(useCount >= item.count):
		item.delete()
	else:
		item.isLock=False
		item.lockUser=None
		item.count-=useCount
		item.save()
	return HttpResponse(json.dumps({"success":True}), content_type="application/json")
